<?php
/*独立会员系统*/
/* 
Plugin Name: 按照用户注册时间排序 
Description: 显示用户注册时间，并按照用户注册时间排序。 
Version: 0.1 
Author: uctheme 
Author URI: http://www.uctheme.com/ 
*/ 

function change_post_menu_label() {
    global $menu;
    global $submenu;
	
    $menu[70][0] = '会员管理';
    $submenu['users.php'][5][0] = '所有会员';
    $submenu['users.php'][10][0] = '添加会员';
    $submenu['users.php'][15][0] = '会员信息';
	
    echo '';
}
add_action( 'admin_menu', 'change_post_menu_label' );
 
add_filter('manage_users_custom_column', 'wpjam_show_users_column_reg_time',11,3); 

function wpjam_show_users_column_reg_time($value, $column_name, $user_id){ 
if($column_name=='reg_time'){ 
$user = get_userdata($user_id); 
return get_date_from_gmt($user->user_registered); 
}else{ 
return $value; 
} 
} 

add_action( 'pre_user_query', 'wpjam_users_search_order' ); 



function wpjam_users_search_order($obj){ 
if(!isset($_REQUEST['orderby']) || $_REQUEST['orderby']=='reg_time' ){ 
if( !in_array($_REQUEST['order'],array('asc','desc')) ){ 
$_REQUEST['order'] = 'desc'; 
} 
$obj->query_orderby = "ORDER BY user_registered ".$_REQUEST['order'].""; 
} 
}






function sj_user_row($actions, $user) {
  
  global $pagenow, $current_user;

  if ($pagenow == 'users.php') {
    if (is_super_admin() || (is_multisite() && current_user_can('administrator'))) {
      if (isset($user->caps['administrator'])) { 
        if ($current_user->ID!=$user->ID) {
          unset($actions['edit']);
          unset($actions['delete']);
          unset($actions['remove']);
        }
      } else {
        unset($actions['edit']);
        unset($actions['delete']);
        unset($actions['remove']);
		$edit_link = esc_url( add_query_arg( 'wp_http_referer', urlencode( stripslashes( $_SERVER['REQUEST_URI'] ) ), "user-edit.php?user_id=$user->ID" ) );
		$user_link = get_author_posts_url($user->ID );
		$actions['edit'] = '<a href="' . $edit_link . '">' . __('Edit') . '</a>';
        $actions['view'] = '<a target="_blank" href="' .$user_link.'">' . __( 'View' ) . '</a>';
		$actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url( "users.php?action=delete&amp;user=$user->ID", 'bulk-users' ) . "'>" . __( 'Delete' ) . "</a>";
		}
    }
  }

  return $actions; 
}

add_action( 'user_row_actions', 'sj_user_row', 10, 2 );




//自定义排列顺序
/*function user_sortable_columns( $columns ) {
	$columns = array(
	   'registered'       => 'registered',
  	    'username'       => 'login',
  	    'email'       => 'email',
  	   
  	);
  	return $columns;
}
add_filter( 'manage_users_sortable_columns', 'user_sortable_columns' );*/

function user_column_orderby( $vars ) {
	
    if ( isset( $vars['orderby'] )) {
        $orderBy = "meta_value";
        if ($vars['orderby'] == "registered"){ $metaKey = "registered"; }

        $vars = array_merge( $vars, array(
            'meta_key' => $metaKey,
            'orderby' => $orderBy
        ));
    }
    return $vars;
}
add_filter( 'request', 'user_column_orderby' );

function sj_user_table( $column ) {
	unset($column['name']);
    $column['nickname'] = __( '昵称' );
    $column['registered'] = __( '注册日期' );
    return $column;
}
 
add_filter( 'manage_users_columns', 'sj_user_table' , 15, 1);
 
function sj_user_table_row( $val, $column_name, $user_id ) {
    $user = get_userdata( $user_id );
	$user_id = $user->ID;
  
    switch ($column_name) {
        case 'registered' :
            return $user->user_registered;
            break;
		case 'nickname' :
            return $user->nickname;
            break;
        default:
    }
 
    return $return;
}
 
add_filter( 'manage_users_custom_column', 'sj_user_table_row', 15, 3 );

function user_photo_upload($redirect,$user_id,$user_photo){

    $message = '';  //reset $message for safety
	require_once(ABSPATH . 'wp-admin/includes/admin.php');  
	//check if it is an image file
	
	  $message = '';
	  //add the user ID to the beginning of the file name to add a stamp to the upload
	  
	  $_FILES['user_photo']['name'] = "uID_" . $user_id . eregi_replace(".+(\..+)","\\1", $_FILES['user_photo']['name']);
	  //media_handle_upload() is what actually does the uploading         
      $filetype = eregi_replace(".+(\..+)","\\1", $_FILES['user_photo']['name']);
	  if ($filetype ==".jpg" ||$filetype ==".gif" || $filetype ==".png") {
	    $id = media_handle_upload('user_photo',''); //post id of Client Files page  
		$userimg = wp_get_attachment_image_src( $id );
		$imgurl = $userimg[0];
		unset($_FILES); 
      
		try{	
			if($message=='') { 
			 //delete the old image
			 if(!empty($user_photo)){
				wp_delete_attachment( $user_photo );
			 }
			 //add, or update the new one
			 update_user_meta($user_id, 'user_photo', $imgurl , false);
			 $message = "Image uploaded";
			 $message = str_replace(" ","%20",$message);
			 }
		   }
		catch (Exception $e) {
			$message = 'Caught%20exception:%20'.  $e->getMessage(). "\n";
			$message = str_replace(" ","%20",$message);
		   }
		//redirect to refresh the page
		wp_redirect( $redirect.'?update='.$message );
	}	
}

//add_action( 'show_user_profile', 'extra_profile_fields' ,10);
//add_action( 'edit_user_profile', 'extra_profile_fields' ,10);

function extra_profile_fields( $user ) { ?>
<table class="form-table">
  <?php 
			global $current_user;
			get_currentuserinfo();
			
			$user_level = $current_user->user_level;
			if ( $user_level >= "8" && $user_level <= "10") {
			
			//头像
			$meta = get_user_meta($user->ID, 'profile');
			$meta = $meta[0];
			$user_photo = get_user_meta($authordata->ID, 'user_photo',true);		
		?>
  <tr>
    <th><label for="user_photo">会员头像</label></th>
    <td><img src="<?php echo $user_photo; ?>"></td>
  </tr>
  <?php } ?>
</table>
<?php }
add_action( 'personal_options_update', 'save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_profile_fields' );

function save_extra_profile_fields( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;
	update_usermeta( $user_id, 'chenghu', $_POST['chenghu'] );
	update_usermeta( $user_id, 'remarks', $_POST['remarks'] );
}

function update_data($user_id,$redirect){
$message = '';
//shorten $_POST arrays to clean up code viewing
$USER = $_POST['USER'];
$META = $_POST['META'];
//add the user ID to update to the User Array
$USER['ID'] = $user_id;

    //password validation - we don't want an empty value, or
	//a value not to our preference (min/max characters, etc)
	if(!empty($USER['user_pass'])){
	  //ensure the password is atleast 6 characters long
	  if(strlen($USER['user_pass']) < 6){ 
		   $message .= 'Password%20must%20be%206%20characters%20or%20more';			   
	  }
	} 
	  else{ unset($USER['user_pass']);} //we filter out the user_pass key when we update
	try{		
	
		update_usermeta( $user_id, 'chenghu', $_POST['chenghu'] );
		update_usermeta( $user_id, 'remarks', $_POST['remarks'] );
		//update_usermeta( $user_id, 'user_star', $_POST['user_star'] );
		
		if(empty($message)){
		  //update the USER data to the wp_user table
		wp_update_user($USER);
           
		  //update our META data
		update_user_meta($user_id, 'profile', $META, false);
		             //print_r($USER);
		  $message .= 'Update%20Successful'; //success message
		}
		else{ throw new Exception($message);}	
	  }
	catch (Exception $e) {
	    //catch any errors and display them
		$message = 'Caught%20exception:%20'.  $e->getMessage(). "\n";
	  }

	//redirect to refresh the page
	wp_redirect( $redirect.'?update='.$message );
}

// 会员搜索
    add_action('pre_user_query', 'sj_user_search_advance');
	function sj_user_search_advance($wp_user_query) {
        if(false === strpos($wp_user_query -> query_where, '@') && !empty($_GET["s"])) {

            global $wpdb;

            $uids=array();

			// get the custom meta fields to search
			$query_metas = 'user_login,nickname,email';
			$query_meta = explode(",",$query_metas);

			$search_metas = "";
			// the escaped query string
			$query_str = mysql_real_escape_string($_GET["s"]);
			
			// add all custom fields into the query
			if(!empty($query_meta)) {
				$search_metas = " OR meta_key='".implode("' OR meta_key='",$wpdb->escape($query_meta))."'";
			}

            $usermeta_affected_ids = $wpdb -> get_results("SELECT DISTINCT user_id FROM ".$wpdb->base_prefix."usermeta WHERE (meta_key='first_name' OR meta_key='last_name'".$search_metas.") AND LOWER(meta_value) LIKE '%".$query_str."%'");

            foreach($usermeta_affected_ids as $quers) {
                array_push($uids,$quers->user_id);
            }

            $users_affected_ids = $wpdb -> get_results("SELECT DISTINCT ID FROM ".$wpdb->base_prefix."users WHERE LOWER(user_nicename) LIKE '%".$query_str."%' OR LOWER(user_email) LIKE '%".$query_str."%'");

            foreach($users_affected_ids as $quers) {
                if(!in_array($quers->ID,$uids)) {
                    array_push($uids,$quers->ID);
                }
            }
			
            $id_string = implode(",",$uids);

            $wp_user_query -> query_where = str_replace("user_nicename LIKE '%".$query_str."%'", "ID IN(".$id_string.")", $wp_user_query -> query_where);
        }
        return $wp_user_query;
    }
?>
